import { isNode as L } from '../nodes/identity.js';
import { Scalar as A } from '../nodes/Scalar.js';
import { YAMLMap as _ } from '../nodes/YAMLMap.js';
import { YAMLSeq as d } from '../nodes/YAMLSeq.js';
import { resolveBlockMap as q } from './resolve-block-map.js';
import { resolveBlockSeq as v } from './resolve-block-seq.js';
import { resolveFlowCollection as b } from './resolve-flow-collection.js';
function u(a, o, c, m, t, l) {
  const i =
      c.type === 'block-map'
        ? q(a, o, c, m, l)
        : c.type === 'block-seq'
          ? v(a, o, c, m, l)
          : b(a, o, c, m, l),
    s = i.constructor;
  return t === '!' || t === s.tagName
    ? ((i.tag = s.tagName), i)
    : (t && (i.tag = t), i);
}
function I(a, o, c, m, t) {
  var n;
  const l = m
      ? o.directives.tagName(m.source, e => t(m, 'TAG_RESOLVE_FAILED', e))
      : null,
    i =
      c.type === 'block-map'
        ? 'map'
        : c.type === 'block-seq'
          ? 'seq'
          : c.start.source === '{'
            ? 'map'
            : 'seq';
  if (
    !m ||
    !l ||
    l === '!' ||
    (l === _.tagName && i === 'map') ||
    (l === d.tagName && i === 'seq') ||
    !i
  )
    return u(a, o, c, t, l);
  let s = o.schema.tags.find(e => e.tag === l && e.collection === i);
  if (!s) {
    const e = o.schema.knownTags[l];
    if (e && e.collection === i)
      o.schema.tags.push(Object.assign({}, e, { default: !1 })), (s = e);
    else
      return (
        e != null && e.collection
          ? t(
              m,
              'BAD_COLLECTION_TYPE',
              `${e.tag} used for ${i} collection, but expects ${e.collection}`,
              !0,
            )
          : t(m, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${l}`, !0),
        u(a, o, c, t, l)
      );
  }
  const f = u(a, o, c, t, l, s),
    r =
      ((n = s.resolve) == null
        ? void 0
        : n.call(s, f, e => t(m, 'TAG_RESOLVE_FAILED', e), o.options)) ?? f,
    p = L(r) ? r : new A(r);
  return (
    (p.range = f.range),
    (p.tag = l),
    s != null && s.format && (p.format = s.format),
    p
  );
}
export { I as composeCollection };
